package com.swk.common.controller;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by Administrator on 2016/4/27.
 */
public class BaseController {
    protected final Logger logger = Logger.getLogger(getClass());
//    protected HttpServletRequest request;
//    protected HttpServletResponse response;
//    protected HttpSession session;
//
//    @ModelAttribute
//    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
//        this.request = request;
//        this.response = response;
//        this.session = request.getSession();
//    }

    public byte[] readPostData(HttpServletRequest request) {
        try {
            InputStream is = request.getInputStream();
            return IOUtils.toByteArray(is);
        } catch (IOException e) {
            logger.error("readPostData error", e);
            return null;
        }
    }

    public String getContentStr(HttpServletRequest request) {
        try {
            byte[] bytes = this.readPostData(request);
            String str = new String(bytes, "UTF-8");
            if (logger.isDebugEnabled()) {
                logger.debug("post content:" + str);
            }
            return str;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("getContentStr error", e);
            return null;
        }
    }

    /**
     * 页面提示信息
     */
    public void printPageMsg(HttpServletResponse response, String msg) throws Exception {
        PrintWriter pw = response.getWriter();
        pw.print(msg);
        pw.flush();
        if (pw != null) {
            pw.close();
        }
    }

    public String httpContextPath(HttpServletRequest request) {
        String httpUrl = "";
        String path = request.getContextPath();
        httpUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        return httpUrl;
    }


    public String getServerIp() {
        String ip = "";
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
            return ip;
        } catch (UnknownHostException e) {
            logger.error("getServerIp error", e);
        }
        return ip;
    }

}
